import { getUserInfo } from './auth';

const LOGS_KEY = 'mall_logs';

// 获取日志列表
export const getLogs = () => {
  const logs = localStorage.getItem(LOGS_KEY);
  return logs ? JSON.parse(logs) : [];
};

// 设置日志列表
export const setLogs = (logs) => {
  // 只保留最近1000条日志
  const recentLogs = logs.slice(0, 1000);
  localStorage.setItem(LOGS_KEY, JSON.stringify(recentLogs));
};

// 添加日志
export const addLog = (logData) => {
  const user = getUserInfo();
  const logs = getLogs();
  
  const newLog = {
    id: Date.now(),
    ...logData,
    operator: logData.operator || user?.nickname || user?.username || '系统',
    operatorId: logData.operatorId || user?.id,
    createTime: Date.now(),
    ipAddress: getIPAddress(),
    device: getDeviceInfo(),
    browser: getBrowserInfo(),
    location: '中国',
    duration: Math.floor(Math.random() * 100) + 50, // 模拟执行时间
    result: logData.result || 'success'
  };
  
  logs.unshift(newLog);
  setLogs(logs);
  
  return newLog;
};

// 获取IP地址（模拟）
const getIPAddress = () => {
  const ips = [
    '192.168.1.100',
    '192.168.1.101',
    '192.168.1.102',
    '10.0.0.50',
    '10.0.0.51'
  ];
  return ips[Math.floor(Math.random() * ips.length)];
};

// 获取设备信息
const getDeviceInfo = () => {
  const userAgent = navigator.userAgent;
  
  if (/mobile/i.test(userAgent)) {
    if (/android/i.test(userAgent)) {
      return 'Android Mobile';
    } else if (/iphone|ipad|ipod/i.test(userAgent)) {
      return 'iOS Mobile';
    }
    return 'Mobile Device';
  }
  
  if (/windows/i.test(userAgent)) {
    return 'Windows PC';
  } else if (/macintosh|mac os x/i.test(userAgent)) {
    return 'Mac';
  } else if (/linux/i.test(userAgent)) {
    return 'Linux';
  }
  
  return 'Desktop';
};

// 获取浏览器信息
const getBrowserInfo = () => {
  const userAgent = navigator.userAgent;
  
  if (/chrome/i.test(userAgent) && !/edge/i.test(userAgent)) {
    return 'Chrome';
  } else if (/safari/i.test(userAgent) && !/chrome/i.test(userAgent)) {
    return 'Safari';
  } else if (/firefox/i.test(userAgent)) {
    return 'Firefox';
  } else if (/edge/i.test(userAgent)) {
    return 'Edge';
  } else if (/opera|opr/i.test(userAgent)) {
    return 'Opera';
  }
  
  return 'Unknown Browser';
};

// 记录操作日志的快捷方法
export const logAction = (module, action, content, result = 'success') => {
  return addLog({
    module,
    action,
    content,
    result
  });
};

// 记录错误日志
export const logError = (module, action, content, errorMessage) => {
  return addLog({
    module,
    action,
    content,
    result: 'fail',
    errorMessage
  });
};

// 清理过期日志（保留90天）
export const cleanExpiredLogs = () => {
  const logs = getLogs();
  const ninetyDaysAgo = Date.now() - 90 * 24 * 60 * 60 * 1000;
  const recentLogs = logs.filter(log => log.createTime > ninetyDaysAgo);
  setLogs(recentLogs);
};